﻿
using Microsoft.Extensions.Configuration;
using OpenIddict.Validation.AspNetCore;
using SageKing.Core.Options;

namespace SageKing.OpenIddict.Resource.Features;

public class OpenIddictResourceFeature : FeatureBase
{
    public OpenIddictResourceFeature(IModule module) : base(module)
    {
    }

    public OpenIdResourceOptions OpenIdOptions { get; set; }

    /// <inheritdoc />
    public override void Apply(IConfigurationManager configurationManager, IHostEnvironment hostEnvironment)
    {
        ArgumentNullException.ThrowIfNull(configurationManager);
        if (OpenIdOptions == null)
        {
            OpenIdOptions = new OpenIdResourceOptions();
            configurationManager.Bind(OpenIdOptions, OpenIdOptions.SectionName);
        }

        Services.AddSingleton(OpenIdOptions);

        Services.AddRouting(o =>
        {
            o.LowercaseUrls = true;
        });

        Services.AddAuthentication(options =>
        {
            options.DefaultScheme
              = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
        });

        // Register the OpenIddict validation components.
        Services.AddOpenIddict()
          .AddValidation(options =>
          {
              // Note: the validation handler uses OpenID Connect discovery
              // to retrieve the address of the introspection endpoint.
              options.SetIssuer(OpenIdOptions.Issuer);
              options.AddAudiences(OpenIdOptions.ClientId);

              // Configure the validation handler to use introspection and register the client
              // credentials used when communicating with the remote introspection endpoint.
              options.UseIntrospection()
                         .SetClientId(OpenIdOptions.ClientId)
                         .SetClientSecret(OpenIdOptions.ClientSecret);

              // Register the System.Net.Http integration.
              options.UseSystemNetHttp();

              // Register the ASP.NET Core host.
              options.UseAspNetCore();
          });


    }
}
